package com.cskaoyan.lifecycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 演示生命周期使用的类
 * @author stone
 * @date 2021/12/27 10:30
 */

public class LifeCycleBean implements BeanNameAware, BeanFactoryAware,
        ApplicationContextAware, InitializingBean, DisposableBean {

    String username;

    String beanName;
    BeanFactory beanFactory;
    ApplicationContext applicationContext;

    public LifeCycleBean() {
        System.out.println("Bean的实例化");
    }

    public void setUsername(String username) {
        System.out.println("设置参数：" + username);
        this.username = username;
    }

    @Override
    public void setBeanName(String beanName) {
        System.out.println("BeanNameAware的setBeanName");
        this.beanName = beanName;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("BeanFactoryAware的setBeanFactory方法");
        this.beanFactory = beanFactory;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("ApplicationContextAware的setApplicationContext方法");
        this.applicationContext = applicationContext;
    }

    public void sayHello() {
        System.out.println(beanName + " say hello world:" + username);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet");
        this.username += " niupi";
    }

    //自定义init方法：方法名任意写
    // 我们需要告知容器这是这个实例的init方法 → bean标签的init-method属性
    public void myinit() {
        System.out.println("自定义init");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean提供的destroy方法");
    }

    public void mydestroy() {
        System.out.println("自定义的destroy");
    }
}
